package com.lz.yz.base.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import it.sauronsoftware.jave.*;

/**
 * 音频工具类
 */
public class AudioUtil {

    private static Logger logger = LoggerFactory.getLogger(AudioUtil.class);

    /**
     * Amr格式音频转为Mp3格式
     */
    public static void changeToMp3(File source, File target) {
        AudioAttributes audio = new AudioAttributes();
        AmrToMp3Encoder encoder = new AmrToMp3Encoder();
        audio.setCodec("libmp3lame");
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        attrs.setAudioAttributes(audio);
        try {
            encoder.encode(source, target, attrs);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InputFormatException e) {
            e.printStackTrace();
        } catch (EncoderException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断文件是不是amr格式
     *
     * @param  fileName  文件名
     * */
    public static boolean isAudioAmr(String fileName) {
        String tmpName = fileName.toLowerCase();
        return  tmpName.endsWith(".amr");
    }


    private static class AmrToMp3Encoder extends Encoder {
        protected void processErrorOutput(EncodingAttributes attributes, BufferedReader errorReader, File source, EncoderProgressListener listener) throws EncoderException, IOException {
            // 屏蔽默认的错误处理
            try {
                String line;
                while ((line = errorReader.readLine()) != null) {
                    logger.debug(line);
                }
            }
            catch (Exception exp) {
                logger.error("file convert error message process failed. ", exp);
            }
        }
    }
}
